package viroyal.com.base.activity.splash;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Parcel;
import android.text.TextUtils;

import com.suntiago.baseui.activity.base.theMvp.model.IModel;
import com.suntiago.baseui.utils.SPUtils;
import com.suntiago.network.network.Api;
import com.suntiago.network.network.BaseRspObserver;
import com.suntiago.network.network.ErrorCode;

import java.util.ArrayList;
import java.util.List;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import viroyal.com.base.AppConfig;
import viroyal.com.base.BuildConfig;
import viroyal.com.base.R;
import viroyal.com.base.activity.main.MainActivity;
import viroyal.com.base.common.ConstantsYJ;
import viroyal.com.base.face.aiwinn.common.Config;
import viroyal.com.base.face.bean.DeviceInfo;
import viroyal.com.base.face.rsp.DeviceInfoRsp;
import viroyal.com.base.net.ApiObserver;
import viroyal.com.base.net.PhpApi;
import viroyal.com.base.net.req.DeviceRegisterRequest;
import viroyal.com.base.net.req.GetSchoolIdRequest;
import viroyal.com.base.net.req.RegisterIOTRequest;
import viroyal.com.base.net.req.TokenRequest;
import viroyal.com.base.net.rsp.DeviceRegisterResponseS;
import viroyal.com.base.net.rsp.GetSchoolIdResponseS;
import viroyal.com.base.net.rsp.RegisterIOTResponseS;
import viroyal.com.base.net.rsp.TokenResponseS;
import viroyal.com.dev.splash.ConfigDevice;

/**
 * Created by zy on 2019/1/25.
 */


public class SplashModel implements IModel {
  @Override
  public int describeContents() {
    return 0;
  }

  @Override
  public void writeToParcel(Parcel dest, int flags) {

  }

  /**
   * 设备自注册
   */
  Subscription deviceRegister(String deviceId, SplashAppDelegate appDelegateBase, Action1<DeviceRegisterResponseS> responseAction1) {
    PhpApi.get().setPhpApiConfig(BuildConfig.PHP_API_HOST, "", 0);
    DeviceRegisterRequest request = new DeviceRegisterRequest(deviceId, "", 0, "新电子班牌设备", 1);
    return PhpApi.get().getPhpApi(ApiObserver.class)
        .deviceRegister(request)
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new BaseRspObserver<>(DeviceRegisterResponseS.class, responseAction1));
  }


  private SplashModel(Parcel in) {
  }

  public SplashModel() {
  }

  public static final Creator<SplashModel> CREATOR = new Creator<SplashModel>() {
    @Override
    public SplashModel createFromParcel(Parcel in) {
      return new SplashModel(in);
    }

    @Override
    public SplashModel[] newArray(int size) {
      return new SplashModel[size];
    }
  };

  public Subscription getSchoolId(String uuid, Action1<GetSchoolIdResponseS> responseAction1) {
    PhpApi.get().setPhpApiConfig(BuildConfig.PHP_API_HOST, "", 0);
    GetSchoolIdRequest request = new GetSchoolIdRequest(uuid);
    return PhpApi.get().getPhpApi(ApiObserver.class)
        .getSchoolId(request)
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new BaseRspObserver<>(GetSchoolIdResponseS.class, responseAction1));
  }

  /**
   * 获取物联网token
   * @param viewDelegate
   * @param tokenRequest
   * @param action1
   * @return
   */
//  public Subscription GetToken(SplashAppDelegate viewDelegate, TokenRequest tokenRequest, Action1<TokenResponseS> action1) {
//    if (viewDelegate == null) {
//      return null;
//    }
//    return PhpApi.get().getPhpApi(ApiObserver.class,BuildConfig.IOT_HOST)
//            .getToken(tokenRequest)
//            .subscribeOn(Schedulers.newThread())
//            .observeOn(AndroidSchedulers.mainThread())
//            .subscribe(new BaseRspObserver<>(TokenResponseS.class, action1));
//  }

  /**
   * 物联网注册
   * @param token
   * @param registerIOTRequest
   * @param viewDelegate
   * @param responseAction1
   * @return
   */
  public Subscription deviceRegister_iot(String token,RegisterIOTRequest registerIOTRequest, SplashAppDelegate viewDelegate, Action1<RegisterIOTResponseS> responseAction1) {
    if (viewDelegate == null) {
      return null;
    }
      return PhpApi.get().getPhpApi(ApiObserver.class, BuildConfig.IOT_HOST)
              .register_iot("Bearer " + token, registerIOTRequest)
              .subscribeOn(Schedulers.newThread())
              .observeOn(AndroidSchedulers.mainThread())
              .subscribe(new BaseRspObserver<>(RegisterIOTResponseS.class, responseAction1));
  }

  private void dismissDialog(AlertDialog sdkAlertDialog) {
    if (null != sdkAlertDialog) {
      sdkAlertDialog.dismiss();
    }
  }

  /**
   * 获取设备硬件信息
   */
  Subscription getDeviceInfo(SplashAppDelegate appDelegateBase,AlertDialog dialog, Context context, Activity activity, Action1<DeviceInfoRsp> action1) {
    if (appDelegateBase == null
            || ConfigDevice.DEMO_MODE
            || TextUtils.isEmpty(Api.get().getApi())) {
      return null;
    }
    return Api.get().getApi(ApiObserver.class)
            .getDeviceInfo(ConfigDevice.school_id, ConfigDevice.getDeviceId())
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new BaseRspObserver<>(DeviceInfoRsp.class, rsp -> {
              if (ErrorCode.isSuccess(rsp.error_code)) {
                if (rsp.extra == null
                        || TextUtils.isEmpty(rsp.extra.is_around_camera+"")
                        || TextUtils.isEmpty(rsp.extra.is_camera_position+"")
                        || TextUtils.isEmpty(rsp.extra.is_infrared+"")) {
                  appDelegateBase.showToast(context.getString(R.string.success_but_no_device_info));
                  dismissDialog(dialog);
                  activity.startActivity(new Intent(activity, MainActivity.class));
                  activity.finish();
                  return;
                }
                List<DeviceInfo.Camera> carmeList = new ArrayList<>();
                carmeList.clear();
                DeviceInfo.Camera camera = new DeviceInfo.Camera(rsp.extra.is_infrared, rsp.extra.is_around_camera, rsp.extra.is_camera_position);
                carmeList.add(camera);
                DeviceInfo deviceInfo = new DeviceInfo(rsp.extra.dpi, rsp.extra.width_val, rsp.extra.height_val, rsp.extra.nfc, carmeList);
//            DeviceInfo deviceInfo = rsp.extra.device_info;
                // 保存硬件信息
                SPUtils.getInstance(context).put(ConstantsYJ.SpTag.DEVICE_INFO, deviceInfo);
                SPUtils.getInstance(context).put(ConstantsYJ.SpTag.DEVICE_APP_INFO, rsp);
                AppConfig.NFC_mode = rsp.extra.nfc;
                if (rsp.extra.verification_mode != null && !rsp.extra.verification_mode.isEmpty()) {
                  if (rsp.extra.verification_mode.size() > 0) {
                    for (int i = 0; i < rsp.extra.verification_mode.size(); i++) {
                      if ("2".equals(rsp.extra.verification_mode.get(i))) {
                        AppConfig.setFace(1, context);
                      }
                    }
                  } else {
                    AppConfig.setFace(0, context);
                  }
                }
                if (null != action1) {
                  action1.call(rsp);
                }
              } else {
                dismissDialog(dialog);
                activity.finish();
                activity.startActivity(new Intent(context, MainActivity.class));
              }
            }));
  }
}
